package com.gszy.auth.service;

import com.gszy.auth.dao.PermissionDao;
import com.gszy.auth.dao.RoleDao;
import com.gszy.auth.dao.UserDao;
import com.gszy.auth.entity.Permission;
import com.gszy.auth.entity.Role;
import com.gszy.auth.entity.Users;
import com.gszy.auth.mvc.BeanFactory;
import com.gszy.auth.security.UserDetails;
import com.gszy.auth.security.UserDetailsService;

import java.util.ArrayList;
import java.util.List;

public class UserService implements UserDetailsService {

    private UserDao userDao = BeanFactory.getInstance(UserDao.class);

    private RoleDao roleDao = BeanFactory.getInstance(RoleDao.class);

    private PermissionDao permissionDao = BeanFactory.getInstance(PermissionDao.class);
    @Override
    public UserDetails loadUserByUsername(String username) {

        Users user = userDao.findUserByUsername(username);

        if (user != null){
            List<Role> roles = roleDao.findRolesByUserId(user.getId());
            List<Permission> permissions = new ArrayList<>();

            for (Role role : roles){
                List<Permission> permissionByRole = permissionDao.findPermissionByRoleId(role.getId());
                permissions.addAll(permissionByRole);
            }
            user.setPermissions(permissions);
        }

        return user;
    }
}
